#!/bin/bash
set -e

file="$1"
msg=$(cat "$file")

# 读取公共常量配置参数 GITLAB_URL + ACCESS_TOKEN + PROJECT_PATHS
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/config.sh"

# 提取格式为 "#123#456" 中的数字，过滤空字符串
IFS="#" read -ra IDS <<<"$msg"
declare -A UNIQUE_ISSUES=()
for id in "${IDS[@]}"; do
  if [[ "$id" =~ ^[0-9]+$ ]]; then
    UNIQUE_ISSUES["$id"]=1
  fi
done

if [ ${#UNIQUE_ISSUES[@]} -eq 0 ]; then
  exit 0
fi

# 如果提交信息中已包含任何路径，不重复添加
for path in "${PROJECT_PATHS[@]}"; do
  if echo "$msg" | grep -q "$path"; then
    exit 0
  fi
done

# 尾部追加对应项目路径和 issue id
echo "" >>"$file"
for iid in "${!UNIQUE_ISSUES[@]}"; do
  for path in "${PROJECT_PATHS[@]}"; do
    encoded_path=$(jq -rn --arg x "$path" '$x|@uri')
    status=$(curl -s -o /dev/null -w "%{http_code}" \
      -H "PRIVATE-TOKEN: $ACCESS_TOKEN" \
      "${GITLAB_URL}/api/v4/projects/${encoded_path}/issues/${iid}")

    if [[ "$status" == "200" ]]; then
      echo "Related to $path#$iid" >>"$file"
      break
    fi
  done
done
